package com.potenza.training.dictionary.controller;

import com.potenza.training.dictionary.entity.ProjectType;
import com.potenza.training.dictionary.entity.TypeOne;
import com.potenza.training.dictionary.server.ProjectTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/hope")
public class ProjectTypeController {

    @Autowired
    private ProjectTypeService projectTypeService;

    static List<TypeOne> typeOneList = new ArrayList<TypeOne>();

    /**
     * 获取所有的项目类型
     * @return
     */
    @GetMapping("/project/type")
    public List<ProjectType> findAll(){
        return projectTypeService.findAll();
    }

    /**
     * 获取经过处理的项目类型
     * @return
     */
    @GetMapping("/project/types")
    public List<TypeOne> edit(){
        typeOneList.clear();
        List<ProjectType> all = findAll();
        for (ProjectType projectType : all) {
            typeOneList.add(new TypeOne(projectType.getId(),projectType.getName(),projectType.getPid(),null));
        }

        List<TypeOne> collect = typeOneList.stream().filter(typeOne ->
                typeOne.getPid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, typeOneList));
            return menu;
        }).collect(Collectors.toList());

        return collect;
    }

    //递归查找所有菜单的子类菜单
    private static List<TypeOne> getChildrens(TypeOne root,List<TypeOne> all){
        List<TypeOne> children = all.stream().filter(linkageEntities -> Long.parseLong(String.valueOf(linkageEntities.getPid()))==root.getId()).map(linkageEntities -> {
            //1、递归找到子菜单
            linkageEntities.setChildren(getChildrens(linkageEntities,all));
            return linkageEntities;
        }).collect(Collectors.toList());
        return children;
    }
}
